/**
 * Created on 19/04/2008
 * 
 */
package com.apbetioli.mapr.project.dao;

import com.apbetioli.mapr.project.entity.Project;
import com.apbetioli.mapr.util.properties.PropertiesLoaderImpl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Alexandre Parra Betioli
 */
class ProjectsDaoNoTransaction implements ProjectsDaoInterface {

    private EntityManagerFactory emf;
    private EntityManager em;
    
    protected ProjectsDaoNoTransaction() {
        em = this.getEntityManager();
    }
    
    private EntityManager getEntityManager() {
        
        if( emf == null )
            emf = Persistence.createEntityManagerFactory( PropertiesLoaderImpl.getValue("config.properties", "persistence.unit") );
        
        return emf.createEntityManager();
    }

    public EntityTransaction getTransaction() {
        return em.getTransaction();
    }
    
    public Project save( final Project project ) {
        
        if(project == null)
            throw new NullPointerException("Project is null");
        
        Project old = findByKey( project.getKey() );

        em.merge( project );
        
        return old;
    }
    
    public Project delete( final String key ) {
        
        Project old = findByKey( key );
    
        if(old != null)
            em.remove( em.merge(old) );
        
        return old;
    }

    public Project findByKey( final String key ) {
        
        if(key == null)
            return null;
        
        Project p = em.find(Project.class, key);
        
        if( p != null )
            return p.clone();
        else 
            return null;
    }
    
    public Project findByName( final String name ) {
        
        if(name == null)
            return null;
        
        Query q =  em.createNamedQuery("Project.findByName");
        q.setParameter("name", name);
        
        try {
          return (Project)q.getSingleResult();
        }
        catch ( NoResultException e ) {
            return null;
        }
    }
    
    public Project findByEmail( final String email ) {
        
        if(email == null)
            return null;        
        
        Query q =  em.createNamedQuery("Project.findByEmail");
        q.setParameter("email", email);
        
        try {
          return (Project)q.getSingleResult();
        }
        catch ( NoResultException e ) {
            return null;
        }
    }
    
    public List<Project> listAll() {
        return em.createNamedQuery("Project.listAll").getResultList();
    }
}
